var CryptoJS = require('../lib/crypto-js');

// 默认的 KEY
var KEY = CryptoJS.enc.Utf8.parse('xLx2GX4RWFQ7yYBg');
/**
 * AES加密 : 字符串 key  返回base64
 */
function encrypt(word, keyStr) {
  let key = KEY
  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
  }

  let srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}

/**
 * AES 解密 : 字符串 key iv  返回base64
 */
function decrypt(word, keyStr, ivStr) {
  let key = KEY
  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
  }

  let base64 = CryptoJS.enc.Base64.parse(word);
  let src = CryptoJS.enc.Base64.stringify(base64);
  var decrypt = CryptoJS.AES.decrypt(src, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });

  var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}


module.exports = {
  encrypt: encrypt,
  decrypt: decrypt,
}